package com.green.service.common.impl;

import java.io.IOException;

import org.apache.log4j.Logger;

import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

import com.green.service.common.FileUploadService;

/**
 * JDK FTP上传实现
 * 
 * @author Hou Peiqin
 *
 */
public class JdkFileUploadServiceImpl implements FileUploadService {
	private final static Logger logger = Logger.getLogger(JdkFileUploadServiceImpl.class);
	private String uploadServer;
	private String accessServer;
	private int port;
	private String username;
	private String password;
	//本地video/picture存放路径
	@SuppressWarnings("unused")
	private String localFilePath;
	
	/**
	 * FTP服务器上复制文件
	 * @param sourceFilePath 源文件路径  
	 * @param targetFilePath 目标文件路径
	 * @return
	 */
	@Override
	public boolean copyFile(String sourceFilePath, String targetFilePath) {
		//TelnetInputStream fis = new TelnetInputStream(srcFile);
		//TelnetOutputStream fos = new TelnetOutputStream(new File(desFile));
		return false;
	}
	
	/**
	 * 上传文件
	 * @param bytes 要上传的文件
	 * @param targetFolderPath 要上传到FTP上的文件路径
	 * @param targetFileName 传到FTP服务器上的文件名
	 * @return 返回文件的HTTP路径
	 */
	public String uploadFile(byte[] bytes, String targetFolderPath, String targetFileName) {
		if(bytes == null) return null;
		
        TelnetOutputStream os = null;
        FtpClient ftpClient = null;
        try {
        	long t1 = System.currentTimeMillis();
        	ftpClient = getFtpClient(targetFolderPath);
        	long t2 = System.currentTimeMillis();
        	logger.info("getFtpClient time = " + (t2- t1));
            os = ftpClient.put(targetFileName);
            os.write(bytes);
            os.flush(); 
        }catch (Exception e) {
        	logger.error(e.getMessage());
			e.printStackTrace();
			return "ERROR";
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if(ftpClient != null) {
					ftpClient.closeServer();
				}
	        }catch (Exception e) {
				e.printStackTrace();
	        }
        }
		return accessServer + "/" + targetFolderPath + "/" + targetFileName;
    }
	
	/**
	 * 上传图片
	 * @param bytes 要上传的图片
	 * @param targetFolderPath 要上传到FTP上的视频路径
	 * @param targetFileName 传到FTP服务器上的文件名
	 * @return 返回文件的HTTP路径
	 */
	@Override
	public String uploadPicture(byte[] bytes, String targetFolderPath, String targetFileName) {
		return uploadFile(bytes, targetFolderPath, targetFileName);
    }
	
	/**
	 * 快照截图的名称，默认规则为xx_p.jpg
	 * @param targetFileName
	 * @return
	 */
	@SuppressWarnings("unused")
	private String videoFileNameToSnapshotFileName(String targetFileName) {
		return targetFileName.substring(0, targetFileName.indexOf(".")) + "_p.jpg";
	}

	protected FtpClient getFtpClient(String folderPath) throws Exception {
		FtpClient ftpClient = new FtpClient();
		ftpClient.openServer(uploadServer, port);
		ftpClient.login(username, password);
		try {
			ftpClient.cd(folderPath);
		} catch (IOException e1) {
			createFolder(ftpClient, folderPath);
		}
		ftpClient.binary();
		return ftpClient;
	}

	private void createFolder(FtpClient ftpClient, String folderPath) throws Exception {
		String[] folders = folderPath.split("/");
		for(String folder : folders) {
			try {
				ftpClient.cd(folder);
			} catch (IOException e1) {
				ftpClient.sendServer("XMKD " + folder + System.getProperty("line.separator"));
				ftpClient.readServerResponse();
				ftpClient.cd(folder);
			}
		}
	}

	@Override
	public String getHttpUrl(String folderPath, String fileName) {
		return "http://" + accessServer + "/" + folderPath + "/original/" + fileName;
	}
	@Override
	public String getHttpFileUrl(String folderPath, String fileName) {
		return "http://" + accessServer + "/" + folderPath + "/" + fileName;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setLocalFilePath(String localFilePath) {
		this.localFilePath = localFilePath;
	}

	public void setUploadServer(String uploadServer) {
		this.uploadServer = uploadServer;
	}

	public void setAccessServer(String accessServer) {
		this.accessServer = accessServer;
	}

}
